<template>
  <!-- 设置报关信息 -->
  <a-modal :width="1200" v-model:visible="showFbaDeclare" title="设置报关信息" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <a-table
      class="table-two-line"
      ref="tableRef"
      row-key="id"
      :data="fbaOrders"
      :span-method="spanMethodAll"
      :scroll="{
        y: 'calc(84vh - 160px)',
      }"
      :columns="tableColumns"
      :expandable="expandable"
      :default-expand-all-rows="true"
      size="mini"
      :bordered="false"
      :pagination="false"
    >
      <template #columns>
        <a-table-column v-for="(item, index) of tableColumns" :fixed="item.fixed" :key="index" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
          <template v-if="item.dataIndex == 'img'" #cell="{ record }">
            <div class="order-w flex">
              <div class="order-detail-item" style="width: 200px">
                <p>
                  <span class="label">发货单号：</span>
                  <span class="highlight">{{ record.billNo }}</span>
                </p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p><span class="label">货件号：</span>{{ record.shipmentId }}</p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p><span class="label">CenterId：</span>{{ record.centerId }}</p>
              </div>
              <div class="order-detail-item" style="width: 200px">
                <p><span class="label">国家：</span>{{ $extract(marketPlaceList[record.marketplaceId], 'name') }}-{{ $extract(marketPlaceList[record.marketplaceId], 'code') }}</p>
              </div>
            </div>
          </template>
          <template v-if="['declareName', 'declareEnName', 'declareCurrency', 'declareAmount', 'declareNum', 'declareNo'].includes(item.dataIndex)" #title>
            <span class="warningColor">*</span>
            <span>{{ item.title }}</span>
          </template>
          <template v-else-if="item.dataIndex == 'declareWeight'" #title>
            <div class="flex-c">
              <span class="warningColor">*</span>
              <span>重量</span>
              <a-select v-model="weightUnit" size="mini" value-key="id" style="width: 60px; margin-left: 4px">
                <a-option value="g" label="g" />
                <a-option value="kg" label="kg" />
              </a-select>
            </div>
          </template>
        </a-table-column>
      </template>
      <template #expand-row="{ record }">
        <a-table class="table-singe-line" row-class="child-row" :show-header="false" row-key="id" :bordered="false" :data="record.skuDetails" size="mini" :pagination="false">
          <template #columns>
            <a-table-column :width="10" />
            <a-table-column v-for="(item, index) of tableColumns" :key="index" :fixed="item.fixed" :align="item.align" :width="item.width" :title="item.title" :data-index="item.dataIndex">
              <template v-if="item.dataIndex == 'img'" #cell="option">
                <ImgPopover :src="option.record.productImg">
                  <template #con>
                    <a-image width="40" height="40" fit="contain" :src="option.record.productImg" />
                  </template>
                </ImgPopover>
              </template>
              <template v-else-if="item.dataIndex == 'msku'" #cell="option">
                <TextLimit :rows="1">{{ option.record.msku || '--' }}</TextLimit>
                <TextLimit :rows="1">{{ option.record.asin || '--' }}</TextLimit>
              </template>
              <template v-else-if="item.dataIndex == 'sku'" #cell="option">
                <TextLimit :rows="1">{{ option.record.sku || '--' }}</TextLimit>
                <p>{{ option.record.cateName || '--' }}</p>
              </template>
              <template v-else-if="item.dataIndex == 'declareName'" #cell="option">
                <div class="cell flex-c">
                  <a-input style="width: 105px" v-model="option.record.declareName" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareName', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareEnName'" #cell="option">
                <div class="cell flex-c">
                  <a-input style="width: 105px" v-model="option.record.declareEnName" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareEnName', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareCurrency'" #cell="option">
                <div class="cell flex-c">
                  <a-select style="width: 75px" v-model="option.record.declareCurrency" value-key="id">
                    <a-option v-for="(key, val) in currencySymbol" :key="key" :value="val" :label="val" />
                  </a-select>
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareCurrency', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareAmount'" #cell="option">
                <div class="cell flex-c">
                  <a-input-number style="width: 80px" v-model="option.record.declareAmount" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareAmount', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareNum'" #cell="option">
                <div class="cell flex-c">
                  <a-input-number style="width: 80px" v-model="option.record.declareNum" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareNum', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareWeight'" #cell="option">
                <div class="cell flex-c">
                  <a-input style="width: 80px" v-model="option.record.declareWeight" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareWeight', option.rowIndex, record.id)" />
                </div>
              </template>
              <template v-else-if="item.dataIndex == 'declareNo'" #cell="option">
                <div class="cell flex-c">
                  <a-input style="width: 80px" v-model="option.record.declareNo" />
                  <icon-double-down v-if="showBatchIcon(record.id, option.rowIndex)" class="edit-icon" @click="setGlobal(option.record, 'declareNo', option.rowIndex, record.id)" />
                </div>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </a-table>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { setFbaShipmentDeclareByStore } from '@/api/purchase'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'

  onMounted(async () => {
    setDefaultData()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const tableColumns: Array<any> = [
    {
      title: '图片',
      dataIndex: 'img',
      width: 60,
    },
    {
      title: 'MSKU/ASIN',
      dataIndex: 'msku',
      width: 100,
    },
    {
      title: 'SKU/类目',
      dataIndex: 'sku',
      width: 100,
    },
    {
      title: '中文名',
      dataIndex: 'declareName',
      width: 140,
    },
    {
      title: '英文名',
      dataIndex: 'declareEnName',
      width: 140,
    },
    {
      title: '币种',
      dataIndex: 'declareCurrency',
      width: 120,
    },
    {
      title: '报关金额',
      dataIndex: 'declareAmount',
      width: 120,
    },
    {
      title: '报关数量',
      dataIndex: 'declareNum',
      width: 120,
    },
    {
      title: '重量',
      dataIndex: 'declareWeight',
      width: 120,
    },
    {
      title: '海关编号',
      dataIndex: 'declareNo',
      width: 120,
    },
  ]

  const expandable = ref<any>({
    title: '',
    defaultExpandAllRows: true,
    expandedRowKeys: [],
    width: 10,
  })
  const showFbaDeclare = ref(props.isShow)
  const fbaOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const weightUnit = ref('g')

  // 添加初始化数据
  async function setDefaultData() {
    fbaOrders.value = JSON.parse(JSON.stringify(props.list))
    expandable.value.expandedRowKeys = fbaOrders.value.map((el: any) => el.id)
    weightUnit.value = fbaOrders.value?.[0]?.skuDetails?.[0].declareWeightUnit || 'g'
  }
  // 合并单元格
  function spanMethodAll(option: any) {
    let { column } = option
    if (column.dataIndex === 'img') {
      return { rowspan: 1, colspan: 10 }
    }
  }
  //设置全局
  async function setGlobal(item: any, key: string, rowIndex: number, parentId: string) {
    let parentIndex = fbaOrders.value.findIndex((el: any) => el.id === parentId)
    const newVal = item[key]
    fbaOrders.value.forEach((el: any, index: number) => {
      if (index === parentIndex) {
        el.skuDetails.forEach((child: any, j: number) => {
          if (j > rowIndex) child[key] = newVal
        })
      } else if (index > parentIndex) {
        el.skuDetails.forEach((child: any) => {
          child[key] = newVal
        })
      }
    })
  }
  // 是否显示批量编辑按钮
  function showBatchIcon(parentId: string, childIndex: number) {
    let parentIndex = fbaOrders.value.findIndex((el: any) => el.id === parentId)
    let parentLen = fbaOrders.value.length
    return !(parentIndex === parentLen - 1 && childIndex === fbaOrders.value[parentIndex].skuDetails.length - 1)
  }
  // 关闭
  function closedDialog() {
    showFbaDeclare.value = false
    emit('closed')
  }
  // 校验必填信息
  function validateData() {
    let flag = true
    fbaOrders.value.forEach((el: any) => {
      el.skuDetails.forEach((child: any) => {
        let keys = ['declareName', 'declareEnName', 'declareCurrency', 'declareAmount', 'declareWeight', 'declareNum', 'declareNo']
        keys.forEach((key: string) => {
          if (!child[key]) flag = false
        })
      })
    })
    if (!flag) Message.error('请检查必填信息是否填写完整~')
    return flag
  }
  // 保存
  async function submitData() {
    if (!validateData()) return false
    let list: Array<any> = []
    fbaOrders.value.forEach((el: any) => {
      let obj = {
        id: el.id,
        skuDetails: el.skuDetails.map((child: any) => {
          child.declareWeightUnit = weightUnit.value
          return child
        }),
      }
      list.push(obj)
    })
    let res: any = await setFbaShipmentDeclareByStore({
      placeLogisticsItems: list,
    })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  :deep(.arco-table-td) {
    background-color: var(--color-fill-1);
  }
  :deep(.arco-table-tr-expand) {
    .arco-table-cell {
      padding: 0;
    }
    .arco-table {
      margin: 0 !important;
      .arco-table-td {
        border-bottom: 1px solid var(--color-neutral-3);
      }
    }
    background-color: #fff !important;
  }
  :deep(.child-row) {
    .arco-table-cell {
      padding: 2px 8px;
    }
  }
  :deep(.arco-table-tr-expand .arco-table-td) {
    background-color: #fff !important;
    border-bottom: none;
  }
  :deep(.arco-table-tr-expand tr:hover .arco-table-td) {
    background-color: var(--color-fill-1) !important;
  }
  :deep(.arco-table-expand .arco-table-cell) {
    display: none;
  }
  .order-w {
    color: #666;
    flex: 1;
    .order-detail-item {
      width: 200px;
    }
  }
  .edit-icon {
    font-size: 16px;
    margin-left: 5px;
    cursor: pointer;
  }
</style>
